package com.ruoyi.business.service.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.ruoyi.business.domain.HistoricActivity;
import com.ruoyi.business.domain.ServiceItem;
import com.ruoyi.business.service.IDefinitionNodeService;
import com.ruoyi.business.service.IProcessService;
import com.ruoyi.business.service.IServiceItemService;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.core.page.TableSupport;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.ISysUserService;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.business.mapper.CarPackageAuditMapper;
import com.ruoyi.business.domain.CarPackageAudit;
import com.ruoyi.business.service.ICarPackageAuditService;
import com.ruoyi.common.core.text.Convert;
import org.springframework.transaction.annotation.Transactional;

/**
 * 审核列Service业务层处理
 * 
 * @author wolfcode
 * @date 2021-07-20
 */
@Service
public class CarPackageAuditServiceImpl implements ICarPackageAuditService 
{
    @Autowired
    private CarPackageAuditMapper carPackageAuditMapper;
    @Autowired
    private IServiceItemService serviceItemService;
    @Autowired
    private IDefinitionNodeService definitionNodeService;
    @Autowired
    private ISysUserService userService;

    @Autowired
    private IProcessService processService;
    /**
     * 查询审核列
     * 
     * @param id 审核列ID
     * @return 审核列
     */
    @Override
    public CarPackageAudit selectCarPackageAuditById(Long id)
    {
        return carPackageAuditMapper.selectCarPackageAuditById(id);
    }

    /**
     * 查询审核列列表
     * 
     * @param carPackageAudit 审核列
     * @return 审核列
     */
    @Override
    public List<CarPackageAudit> selectCarPackageAuditList(CarPackageAudit carPackageAudit)
    {
        carPackageAudit.setCreateBy(ShiroUtils.getUserId().toString());
        List<CarPackageAudit> carPackageAudits = carPackageAuditMapper.selectCarPackageAuditList(carPackageAudit);
        for (CarPackageAudit audit:carPackageAudits){
            audit.setServiceItem(JSON.parseObject(audit.getServiceItemInfo(), ServiceItem.class));
            //跟腱炎数据中的流程实例id查询任务名称
            Task currentTask = processService.getTaskByProcessInstanceId(audit.getInstanceId());
            if (currentTask!=null){
                //currentTask!= null ,说明任务未结束
                audit.setTaskId(currentTask.getId());
                audit.setTaskName(currentTask.getName());
            }else {
                //currentTask!= null ,说明任务已结束
                audit.setTaskName("任务结束");
            }
        }
        return carPackageAudits;
    }

    /**
     * 新增审核列
     * 
     * @param carPackageAudit 审核列
     * @return 结果
     */
    @Override
    public int insertCarPackageAudit(CarPackageAudit carPackageAudit)
    {
        carPackageAudit.setCreateTime(DateUtils.getNowDate());
        return carPackageAuditMapper.insertCarPackageAudit(carPackageAudit);
    }

    /**
     * 修改审核列
     * 
     * @param carPackageAudit 审核列
     * @return 结果
     */
    @Override
    public int updateCarPackageAudit(CarPackageAudit carPackageAudit)
    {
        return carPackageAuditMapper.updateCarPackageAudit(carPackageAudit);
    }

    /**
     * 删除审核列对象
     * 
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteCarPackageAuditByIds(String ids)
    {
        return carPackageAuditMapper.deleteCarPackageAuditByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除审核列信息
     * 
     * @param id 审核列ID
     * @return 结果
     */
    @Override
    public int deleteCarPackageAuditById(Long id)
    {
        return carPackageAuditMapper.deleteCarPackageAuditById(id);
    }

    @Override
    public void cancelApply(String instanceId, Long carPackageAuditId) {
        CarPackageAudit audit = carPackageAuditMapper.selectCarPackageAuditById(carPackageAuditId);
        audit.setStatus(CarPackageAudit.STATUS_CANCEL);
        audit.setAuditors("");
        carPackageAuditMapper.updateCarPackageAudit(audit);
        ServiceItem item = JSON.parseObject(audit.getServiceItemInfo(),ServiceItem.class);
        item.setAuditStatus(ServiceItem.AUDITSTATUS_INIT);
        serviceItemService.updateServiceItemNoCondition(item);
        //撤销流程
        processService.deleteProcessInstance(instanceId);
    }

    @Override
    public List<CarPackageAudit> selectTodoList(CarPackageAudit carPackageAudit) {
        //获取到当前登录用户的id,根据id查询待办任务
        String userId = ShiroUtils.getUserId().toString();
        Long count = processService.getTodoTaskCount(CarPackageAudit.DEFINITION_KEY,userId);
        if (count > 0){
            //查询符合条件的记录有多少条
            PageDomain pageDomain = TableSupport.buildPageRequest();
            Integer pageNum = pageDomain.getPageNum();
            Integer pageSize = pageDomain.getPageSize();
            Integer startNum = (pageNum - 1)*pageSize;
            //如果符合条件的记录数大于0,才进来集合的查询
            List<Task> taskList = processService.selectTodoTaskList(
                    CarPackageAudit.DEFINITION_KEY,
                    userId,
                    startNum,
                    pageSize);
            List<CarPackageAudit> resultList = new ArrayList<>();
            for (Task task : taskList) {
                ProcessInstance instance = processService.getprocessInstanceById(task.getProcessInstanceId());
                String businessKey = instance.getBusinessKey();
                CarPackageAudit audit = carPackageAuditMapper.selectCarPackageAuditById(Long.parseLong(businessKey));
                audit.setServiceItem(JSON.parseObject(audit.getServiceItemInfo(),ServiceItem.class));
                audit.setTaskId(task.getId());
                audit.setTaskName(task.getName());
                resultList.add(audit);
            }
            Page page = new Page();
            page.setTotal(count);
            page.setPageNum(pageNum);
            page.setPageSize(pageSize);
            page.addAll(resultList);
            return page;
        }else{
            return Collections.EMPTY_LIST;
        }

    }

    @Override
    public void complete(String taskId, Boolean auditStatus, String comment) {
        //任务处理
        Task task = processService.getTaskByTaskId(taskId);
        ProcessInstance processInstance = processService.getprocessInstanceById(task.getProcessInstanceId());
        String businessKey = processInstance.getBusinessKey();
        //  任务属于候选人任务,先领取.
        //  给任务添加批注信息
        //  给任务添加流程变量 流程变量的名字当前处理任务的id  流程的值 auditStatus
        processService.claimAndComplete(task,ShiroUtils.getUserId().toString(),auditStatus,comment);

        //判断流程是否已经结束了.
        //如果流程结束了,审核就通过
        //如何判断流程已经结束了?
        Task nextTask = processService.getTaskByProcessInstanceId(task.getProcessInstanceId());
        //根据流程实例ID获取下一个节点. 下一个节点为空: 流程已经结束,审核通过  下一个不为空: 流程没有结束
        CarPackageAudit audit = carPackageAuditMapper.selectCarPackageAuditById(Long.parseLong(businessKey));
        if (nextTask == null){
            //下一个节点为空: 流程已经结束
            //    t_car_package_audit和t_service_item修改审核状态
            audit.setStatus(CarPackageAudit.STATUS_PASS);
            audit.setAuditors("");
            ServiceItem item = JSON.parseObject(audit.getServiceItemInfo(),ServiceItem.class);
            item.setAuditStatus(ServiceItem.AUDITSTATUS_APPROVED);
            serviceItemService.updateServiceItemNoCondition(item);
        }else{
            //下一个节点不为空: 流程节点没有结束
            if (auditStatus){
                //    如果auditStatus为true
                //        根据下一个节点的Id在t_definition_node寻找该节点的审核人,给该节点设置候选人
                List<String> userNameList = new ArrayList<>();
                String taskDefinitionKey = nextTask.getTaskDefinitionKey();
                List<SysUser> auditors = definitionNodeService.queryByTaskDefinitionKey(taskDefinitionKey);
                for (SysUser user:auditors){
                    processService.addCandidateUser(nextTask,user.getUserId());
                    userNameList.add(user.getUserName());
                }
                audit.setAuditors(JSON.toJSONString(userNameList));
            }else {
                //    如果auditStatus为false
                //        获取到该流程发起人,给当前节点设置对应的候选人为当前流程发起人
                processService.addCandidateUser(nextTask,Long.parseLong(audit.getCreateBy()));
                //        t_car_package_audit状态修改成审核拒绝 1
                audit.setAuditors(audit.getCreateByName());
                audit.setStatus(CarPackageAudit.STATUS_REJECT);
            }
        }
        carPackageAuditMapper.updateCarPackageAudit(audit);
    }

    @Override
    @Transactional
    public void serviceUpdateServiceItem(Long carPackageAuditId, ServiceItem serviceItem) {
        serviceItemService.updateServiceItemNoCondition(serviceItem);
        CarPackageAudit audit = carPackageAuditMapper.selectCarPackageAuditById(carPackageAuditId);
        audit.setServiceItemInfo(JSON.toJSONString(serviceItem));
        carPackageAuditMapper.updateCarPackageAudit(audit);

    }

    @Override
    @Transactional
    public void reApply(String taskId, Long carPackageAuditId) {
        //添加批注,领取任务,完成任务
        Task task = processService.getTaskByTaskId(taskId);
        processService.claimAndComplete(task,ShiroUtils.getUserId().toString(),"重新申请");
        //设置流程变量
        Task nextTask = processService.getTaskByProcessInstanceId(task.getProcessInstanceId());
        CarPackageAudit audit = carPackageAuditMapper.selectCarPackageAuditById(carPackageAuditId);
        ServiceItem item = JSON.parseObject(audit.getServiceItemInfo(),ServiceItem.class);
        processService.setVariable(nextTask.getId(),"money",item.getDiscountPrice().longValue());
        //
        String taskDefinitionKey = nextTask.getTaskDefinitionKey();
        List<SysUser> sysUsers = definitionNodeService.queryByTaskDefinitionKey(taskDefinitionKey);
        List<String> auditors = new ArrayList<>();
        //查询下一个节点,查询对应候选人,给任务添加候选人
        //根据carPackageAuditId查询carPackageAudit对象
        for (SysUser user:sysUsers){
            processService.addCandidateUser(nextTask,user.getUserId());
            auditors.add(user.getUserName());
        }
        //更新carPackageAudit对象的auditors字段
        audit.setStatus(CarPackageAudit.STATUS_IN_ROGRESS);
        audit.setAuditors(JSON.toJSONString(auditors));
        carPackageAuditMapper.updateCarPackageAudit(audit);
    }

    @Override
    public List<CarPackageAudit> selectTaskList(CarPackageAudit carPackageAudit) {
        //获取当前登录用户的id
        String  userId = ShiroUtils.getUserId().toString();
        //获取已办任务总数
        Long count = processService.getHistoricTaskCount(CarPackageAudit.DEFINITION_KEY,userId);
        if(count>0){
            PageDomain pageDomain = TableSupport.buildPageRequest();
            Integer pageNum = pageDomain.getPageNum();
            Integer pageSize = pageDomain.getPageSize();
            Integer startNum = (pageNum-1)*pageSize;
            List<HistoricTaskInstance> historicTaskInstanceList =
                    processService.selectHistoricTaskList(
                            CarPackageAudit.DEFINITION_KEY,
                            userId,
                            startNum,
                            pageSize
                            );
            //3.遍历待办任务,查询对应的CarPackAgeAudit
            List<CarPackageAudit> resultList = new ArrayList<>();
            for (HistoricTaskInstance task : historicTaskInstanceList) {
                HistoricProcessInstance instance = processService
                        .getHistoricProcessInstanceById(task.getProcessInstanceId());
                String businessKey = instance.getBusinessKey();
                CarPackageAudit audit = carPackageAuditMapper.selectCarPackageAuditById(Long.parseLong(businessKey));
                audit.setServiceItem(JSON.parseObject(audit.getServiceItemInfo(),ServiceItem.class));
                audit.setTaskName(task.getName());
                audit.setDoneTime(task.getEndTime());
                audit.setTaskId(task.getId());
                resultList.add(audit);
            }
            Page page = new Page();
            page.setTotal(count);
            page.setPageNum(pageNum);
            page.setPageSize(pageSize);
            page.addAll(resultList);
            return page;
        }else{
            return Collections.EMPTY_LIST;
        }
    }

    @Override
    public List<HistoricActivity> listHistory(String instanceId) {
        List<HistoricActivityInstance> historicActivityInstances = processService.selectHistoricActivityList(instanceId);
        //返回的结果集
        List<HistoricActivity> resultList = new ArrayList<>();
        for (HistoricActivityInstance instance:historicActivityInstances){
            HistoricActivity activity = new HistoricActivity();
            //把instance的所有属性值赋值给activity
            BeanUtils.copyProperties(instance,activity);
            //查询批注信息
            String comment = processService.getComment(activity.getTaskId());
            activity.setComment(comment);
            //设置任务处理人
            String assignee = activity.getAssignee();
            if (StringUtils.isNotEmpty(assignee)){
                SysUser sysUser = userService.selectUserById(Long.parseLong(assignee));
                activity.setAssigneeName(sysUser.getUserName());
            }
            resultList.add(activity);
        }
        return resultList;
    }

}
